package org.wevil.controller.sys;

import org.wevil.enumu.ResultEnum;
import org.wevil.service.sys.ResService;
import org.wevil.vo.Result;
import org.wevil.vo.list.ResListVo;



import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Validated
/** 资源管理 */
@RestController
@RequestMapping("/res")
public class ResController {

    @Resource
    private ResService resService;

    /** 根据id获取资源信息 */
    @GetMapping("/{id}")
    public Result<?> get(
             @PathVariable Integer id
    ) {
        ResListVo data = resService.getById(id);
        return Result.success(data);
    }

    // ---------------------------------------------------上传----------------------------------------------------//

    /** 单文件上传 */
    @PostMapping("/up/single")
    public Result<ResListVo> singleFile(
             @RequestParam MultipartFile file
    ) {
        // 没有文件直接返回
        if (Objects.isNull(file) || file.isEmpty()) {
            return Result.info(ResultEnum.PARAMS);
        }
        // 上传
        ResListVo data = resService.upload(file);
        return Result.success(data);
    }

    /** 多文件上传 */
    @PostMapping(value = "/up/multi")
    public Result<List<ResListVo>> uploadMulti(
             @RequestParam("files") MultipartFile[] files
    ) {
        // 没有文件直接返回
        if (Objects.isNull(files)) {
            return Result.info(ResultEnum.PARAMS);
        }
        // 多文件上传
        List<ResListVo> data = new ArrayList<>();
        for (MultipartFile file : files) {
            ResListVo resListVo = resService.upload(file);
            data.add(resListVo);
        }
        return Result.success(data);
    }

    // ---------------------------------------------------下载----------------------------------------------------//

    /** 根据资源id下载 */
    @GetMapping("/download/{id}")
    public void downloadById(
             @PathVariable Integer id
    ) {
        resService.downloadById(id);
    }

    /** 根据文件名下载 */
    @GetMapping("/download")
    public void downloadByName(
             @RequestParam(required = false) String fileRelativePath,
             @RequestParam String fileName
    ) {
        resService.downloadByName(fileRelativePath, fileName);
    }
}